package com.gamota.mobi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidquery.AQuery;

import com.easy.facebook.android.apicall.GraphApi;
import com.easy.facebook.android.data.Person;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;
import com.gamota.mobi.util.Constants;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class FBFriendListActivity extends ListActivity implements LoginListener, OnClickListener, OnItemClickListener {
	
	private AQuery aq;
	private String FB_APP_ID;
	private FBLoginManager fbLoginManager;
	private ArrayList<Person> friendList;
	private boolean checkboxStates[];
	private FriendAdapter adapter;
	private EditText inputSearch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_fb_friend_list);
		EasyTracker.getInstance().setContext(this);
		aq = new AQuery(this);
		aq.id(R.id.btn_done_tag).clicked(this);
		inputSearch = (EditText) findViewById(R.id.inputSearch);
		konnectFacebook();
		friendList = new ArrayList<Person>();
		adapter = new FriendAdapter(this, R.layout.fb_friend_item, friendList);
		getListView().setAdapter(adapter);
		getListView().setOnItemClickListener(this);
		inputSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				adapter.getFilter().filter(s.toString().toLowerCase(Locale.US));
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		EventBus.getDefault().register(this);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}
	
	private void konnectFacebook(){
		String permissions[] = {"email", "read_stream","publish_stream", "read_friendlists"};
		FB_APP_ID = getResources().getString(R.string.fb_app_id);
		fbLoginManager = new FBLoginManager(this, R.layout.activity_login, FB_APP_ID, permissions);
		if(fbLoginManager.existsSavedFacebook()){
			fbLoginManager.loadFacebook();
		} else {
			fbLoginManager.login();
		}
	}
	
	public void onEventMainThread(final List<Person> list){
		checkboxStates = new boolean[list.size()*2];
		aq.id(R.id.fb_progress).gone();
		aq.id(inputSearch).visible();
		getListView().setVisibility(View.VISIBLE);
		for(Person p : list){
			friendList.add(p);
		}
		Collections.sort(friendList, new Comparator<Person>() {
			@Override
			public int compare(Person lhs, Person rhs) {
				// TODO Auto-generated method stub
				return lhs.getName().compareTo(rhs.getName());
			}
		});
		adapter.notifyDataSetChanged();
	}
	
	@Override
	public void loginSuccess(Facebook facebook) {
		// TODO Auto-generated method stub
		final GraphApi graph = new GraphApi(facebook);
		AsyncExecutor.create().execute(new RunnableEx() {
			@Override
			public void run() throws Exception {
				// TODO Auto-generated method stub
				List<Person> list = graph.getAllFriends();
				EventBus.getDefault().post(list);
			}
		});
	}

	@Override
	public void logoutSuccess() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void loginFail() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		fbLoginManager.loginSuccess(data);
	}
	
	private class FriendAdapter extends ArrayAdapter<Person> {
		
		private AQuery aq;

		public FriendAdapter(Context context, int textViewResourceId, ArrayList<Person> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHoler holder = null;
			if(convertView == null){
				convertView = getLayoutInflater().inflate(R.layout.fb_friend_item, null);
				holder = new ViewHoler();
				holder.image = (ImageView) convertView.findViewById(R.id.picture);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
				convertView.setTag(holder);
			} else {
				holder = (ViewHoler) convertView.getTag();
			}
			final Person person = getItem(position);
			if(person != null){
				aq = new AQuery(convertView);
				Bitmap placeholder = aq.getCachedImage(R.drawable.ic_loading);
				if (aq.shouldDelay(position, convertView, parent, person.getPicture())) {
					aq.id(holder.image).image(placeholder, AQuery.RATIO_PRESERVE);
				} else {
					aq.id(holder.image).image(person.getPicture(), true, true, 0, 0, placeholder, AQuery.FADE_IN_NETWORK, AQuery.RATIO_PRESERVE);
				}
				aq.id(holder.name).text(person.getName());
				holder.checkBox.setTag(position);
				holder.checkBox.setChecked(person.isChecked());
				holder.checkBox.setOnClickListener(new View.OnClickListener() {
			           public void onClick(View v) {
			               if(((CheckBox)v).isChecked()){
			            	   checkboxStates[position] = true;
			                   person.setChecked(true);
			               } else{
			            	   checkboxStates[position] = false;
			                   person.setChecked(false);
			               }
			            }
			    });
			}
			return convertView;
		}
		
	}
	
	private static class ViewHoler {
		ImageView image;
		TextView name;
		CheckBox checkBox;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_done_tag:
			List<String> idList = new ArrayList<String>();
			List<String> nameList = new ArrayList<String>();
			String ids = "";
			String names = "";
			for(int i=0; i<friendList.size(); i++){
				if(friendList.get(i).isChecked()){
					idList.add(friendList.get(i).getId());
					nameList.add(friendList.get(i).getName());
				}
			}
			ids = TextUtils.join(",", idList);
			if(nameList.size() == 0){
				names = "";
			} else if(nameList.size() == 1){
				names = getResources().getString(R.string.with) + " " + nameList.get(0);
			} else if(nameList.size() == 2){
				names = getResources().getString(R.string.with) + " " + nameList.get(0) + " " + getResources().getString(R.string.and) + " " + nameList.get(1);
			} else {
				names = getResources().getString(R.string.with) + " " + nameList.get(0) + " " + String.format(getResources().getString(R.string.with_and_others), nameList.size() - 1);
			}
			Intent i = getIntent();
			i.putExtra(Constants.FB_USER_IDS, ids);
			i.putExtra(Constants.FB_USER_NAMES, names);
			setResult(RESULT_OK, i);
			finish();
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		setResult(RESULT_CANCELED);
		super.onBackPressed();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long arg3) {
		// TODO Auto-generated method stub
		Person person = (Person) parent.getItemAtPosition(position);
		if(person.isChecked()){
			person.setChecked(false);
			checkboxStates[position] = false;
		} else {
			person.setChecked(true);
			checkboxStates[position] = true;
		}
		adapter.notifyDataSetChanged();
	}
}
